import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
import { login, getInfo, getUserDetailById } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
    },
    // 删除token
    delToken(state) {
      state.token = ''
      removeToken()
    },
    // 设置用户信息
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    // 删除用户信息
    delUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 用户登录
    async userLogin(context, payload) {
      const { data } = await login(payload)
      console.log(data)
      context.commit('setToken', data)
      // 存入时间戳
      setTimeStamp()
    },

    // 用户信息
    async getUserInfo(context) {
      const res = await getInfo()
      const info = await getUserDetailById(res.data.userId)
      context.commit('setUserInfo', { ...res.data, ...info.data })
    },
    // 用户退出
    logout(context) {
      // 删除token
      context.commit('delToken')
      // 删除userInfo
      context.commit('delUserInfo')
    }
  }
}

